package xyz.hellothomas.sftp.client.core;

import com.jcraft.jsch.*;

import java.util.Properties;

/**
 * @author Thomas
 * @date 2022/2/13 10:46
 * @description
 * @version 1.0
 */
public class SftpClient {

    private static final String CHANNEL_TYPE = "sftp";
    private static final Properties SSH_CONFIG = new Properties();
    private Session session;
    private ChannelSftp channelSftp;

    static {
        SSH_CONFIG.put("StrictHostKeyChecking", "no");
    }

    public SftpClient(String host, int port, String username, String password, int connectTimeout) {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig(SSH_CONFIG);
            session.setTimeout(connectTimeout);
            session.connect();
            this.session = session;
            ChannelSftp channelStp = (ChannelSftp) session.openChannel(CHANNEL_TYPE);
            channelStp.connect();
            this.channelSftp = channelStp;
        } catch (JSchException e) {
            throw new RuntimeException("连接sftp失败", e);
        }
    }

    public void close() {
        if (channelSftp != null && channelSftp.isConnected()) {
            channelSftp.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }

    public boolean test() {
        if (channelSftp != null && channelSftp.isConnected()) {
            try {
                channelSftp.cd("./");
                return true;
            } catch (SftpException e) {
                return false;
            }
        }

        return false;
    }

    public ChannelSftp getChannelSftp() {
        return channelSftp;
    }
}
